package com.qjdchina.sku.biz.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import com.qjdchina.sku.biz.*;
import com.qjdchina.sku.dao.mapper.*;
import com.qjdchina.sku.enums.ItemValueType;
import com.qjdchina.sku.model.*;
import com.qjdchina.sku.model.vo.*;
import com.qjdchina.sku.util.CategoryBrandBusiUtil;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.qjdchina.commons.enums.IsDeleted;
import com.qjdchina.commons.model.PageModel;
import com.qjdchina.commons.result.Result;
import com.qjdchina.sku.converter.BrandConverter;
import com.qjdchina.sku.converter.CategoryConverter;
import com.qjdchina.sku.converter.SkuGroupConverter;
import com.qjdchina.sku.converter.SkuProductConverter;
import com.qjdchina.sku.enums.AuditStatus;
import com.qjdchina.sku.enums.IsProductCollection;
import com.qjdchina.sku.enums.PicturePathType;
import com.qjdchina.sku.model.query.SkuProductQueryVO;
import com.qjdchina.sku.service.enums.SkuResultCode;

@Service
public class SkuProductManagerImpl implements SkuProductManager {

	public static final Logger LOGGER = LoggerFactory.getLogger(SkuProductManagerImpl.class);

	@Autowired
	private SkuProductMapper skuProductMapper;
	@Autowired
	private SkuGroupMapper skuGroupMapper;
	@Autowired
	private SkuItemMapper skuItemMapper;
	@Autowired
	private RelProductSkuAttributeMapper relProductSkuAttributeMapper;
	@Autowired
	private BrandMapper brandMapper;
	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private Validator validator;
	@Value("#{sku['fs.rest.request.url']}")
	private String restfulUrl;
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private SkuCompanyManager skuCompanyManager;
	@Autowired
	private ProductPictureManager productPictureManager;
	@Autowired
	private CategoryManager categoryManager;

	@Autowired
	private CategoryBrandAssociateMapper categoryBrandAssociateMapper;

	@Autowired
	private CategoryBrandBusiUtil categoryBrandBusiUtil;

	@Autowired
	private SkuItemManager skuItemManager;

	@Autowired
	private CaseStoreInfoMapper caseStoreInfoMapper;
	/**
     * 根据品类获取品牌 
     * shenpingfeng
     * 2016年11月22日
     * @return
     */
	@Override
	public Result<PageModel<SkuProductVO>> queryPagedProductList(SkuProductQueryVO skuProductQueryVO,
			PageModel<SkuProductVO> pageModel) {
		if (skuProductQueryVO == null) {
			return new Result<PageModel<SkuProductVO>>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		Map<String, Object> params = convertSkuProductQueryVOToMap(skuProductQueryVO);
		int pagedProductTotal = skuProductMapper.getPagedProductTotal(params,skuProductQueryVO.getAuditStatusList());
		List<SkuProduct> skuProducts = skuProductMapper.queryPagedProductList(params,skuProductQueryVO.getAuditStatusList(), pageModel);
		List<SkuProductVO> skuProductVOs = SkuProductConverter.toSkuProductVOs(skuProducts);
		pageModel.setPagedRecords(skuProductVOs);
		pageModel.setTotalCount(pagedProductTotal);
		return new Result<PageModel<SkuProductVO>>(pageModel);
	}

	private Map<String, Object> convertSkuProductQueryVOToMap(SkuProductQueryVO queryVO) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

		Map<String, Object> params = new HashMap<String, Object>();

		try {
			if (StringUtils.isNotBlank(queryVO.getAuditTimeStart())) {
				params.put("auditTimeStart", simpleDateFormat.parse(queryVO.getAuditTimeStart()));
			}
			if (StringUtils.isNotBlank(queryVO.getAuditTimeEnd())) {
				params.put("auditTimeEnd", simpleDateFormat.parse(queryVO.getAuditTimeEnd()));
			}
			params.put("productId", queryVO.getProductId());
			params.put("productName", queryVO.getProductName());
			params.put("productCode", queryVO.getProductCode());
			params.put("auditStatus", queryVO.getAuditStatus());
			params.put("skuBrandId", queryVO.getSkuBrandId());
			params.put("skuCategoryId", queryVO.getSkuCategoryId());
			params.put("skuItemId", queryVO.getSkuItemId());
			params.put("value", queryVO.getValue());
			params.put("companyName", queryVO.getCompanyName());
			params.put("skuUserId", queryVO.getSkuUserId());
			params.put("companyId", queryVO.getCompanyId());
			if(queryVO.getPriceStart() != null){
				params.put("priceStart", queryVO.getPriceStart());
			}
			if(queryVO.getPriceEnd() != null){
				params.put("priceEnd", queryVO.getPriceEnd());
			}
			
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return params;

	}

	@Override
	public Result<SkuProductCompareVO> productCompare(Integer[] ids, RolePrice rolePrice) {

		// 返回的对象
		SkuProductCompareVO skuProductCompareVO = new SkuProductCompareVO();

		// 参数校验
		if (null == ids || ids.length == 0) {
			LOGGER.warn("parameter is null !");
			return new Result<SkuProductCompareVO>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}

		Integer categoryId = null;
		// 对比的产品
		List<SkuProductVO> products = new ArrayList<>();
		for (Integer id : ids) {
			SkuProduct skuProduct = skuProductMapper.selectByPrimaryKey(id);

			// 数据不存在
			if (null == skuProduct) {
				LOGGER.warn("product not exist ! product id is {}", id);
				return new Result<SkuProductCompareVO>(SkuResultCode.DATA_NOT_EXIST);
			}

			// 判断品类是否一致，品类不同不能比较
			Integer skuCategoryId = skuProduct.getSkuCategoryId();
			if (null == categoryId) {
				categoryId = skuCategoryId;
			} else {
				if (categoryId.compareTo(skuCategoryId) != 0) {
					return new Result<SkuProductCompareVO>(SkuResultCode.CATEGORY_NOT_IDENTICAL);
				}
			}
			SkuProductVO skuProductVO = SkuProductConverter.toSkuProductVO(skuProduct);

			//查询品类
			Result<Category> resultCategory = categoryManager.getCagegorysById(skuCategoryId);
			if(!resultCategory.isSuccess()){
				return new Result<SkuProductCompareVO>(SkuResultCode.DATA_NOT_EXIST);
			}
			Category category = resultCategory.getDataModel();
			CategoryMenuVO categoryVO = CategoryConverter.toCategoryVO(category);
			skuProductVO.setCategoryVO(categoryVO);

			//查询品牌
			BrandVO brandVO = brandMapper.selectByCategoryIdAndBrandId(skuCategoryId, skuProductVO.getSkuBrandId());
			//查询获取品类品牌属性值
			List<CategoryBrandAssoVO> categoryBrandAssoVOList = getCategoryBrandAssoVOList(skuProductVO.getSkuCategoryId(),
					brandVO.getCategoryBrandId());
			//获取部品详情页品类品牌属性值映射
			Map<String, Object> resultMap = getCategoryBrandAssoMap(categoryBrandAssoVOList);
			brandVO.setCategoryBrandAssoMap(resultMap);
			//查询获取品类品牌运费调差值
			List<CategoryBrandRegionVO> categoryBrandRegionVOList = categoryBrandBusiUtil.getCategoryBrandRegionVOList(brandVO
					.getCategoryBrandId());
			brandVO.setCategoryBrandRegionVOList(categoryBrandRegionVOList);
			skuProductVO.setBrandVO(brandVO);
			
			//查询公司信息
			Integer companyId = skuProductVO.getCompanyId();
			Result<SkuCompanyVO> result = skuCompanyManager.findSkuCompanyByCompanyId(companyId);
			if(result.isSuccess()){
				SkuCompanyVO skuCompanyVO = result.getDataModel();
				skuProductVO.setCompanyName(skuCompanyVO.getCompanyName());
			}	
			
			//查询产品图片
			Result<List<ProductPictureVO>> resultProductPidcture = productPictureManager
					.findProductPictureByProductId(id);
			List<ProductPictureVO> productPictureVOs = resultProductPidcture.getDataModel();
			skuProductVO.setProductPictureVOs(productPictureVOs);

			//查询战略价表头
			Result<Integer> strategicSkuItemIdRes = skuItemManager.getStrategicSkuItemId(skuProduct.getSkuCategoryId());
			Integer strategicSkuItemId = null;
			if (strategicSkuItemIdRes.isSuccess()) {
				strategicSkuItemId = strategicSkuItemIdRes.getDataModel();
			}
			Result<List<SkuItem>> skuItemListRes = skuItemManager.selectByCategoryIdAndSkuNameLike(skuProduct.getSkuCategoryId()
					, "战略合作施工价");
			Integer constructItemId = null;
			if (skuItemListRes.isSuccess()) {
				if (skuItemListRes.getDataModel() != null && skuItemListRes.getDataModel().size() > 0) {
					constructItemId = skuItemListRes.getDataModel().get(0).getId();
				}
			}

			// 查询产品的sku
			List<RelProductSkuAttributeVO> relProductSkuAttributeVOList = relProductSkuAttributeMapper
					.getByproduct(skuProduct.getProductId());
			List<RelProductSkuAttributeVO> byproduct = new LinkedList<>();
			List<RelProductSkuAttributeVO> optionProduct = new LinkedList<>();
			if (relProductSkuAttributeVOList != null && relProductSkuAttributeVOList.size() > 0) {
				for (RelProductSkuAttributeVO relProductSkuAttributeVO : relProductSkuAttributeVOList) {
					if (!ItemValueType.MUILT_SELCT.getValue().equals(relProductSkuAttributeVO.getValueType())) {
						if ((relProductSkuAttributeVO.getSkuItemId().equals(constructItemId) || relProductSkuAttributeVO.getSkuItemId()
								.equals(strategicSkuItemId)) && "1".equals(rolePrice.getIsShow())) {
							relProductSkuAttributeVO.setValue("****");
						}
						byproduct.add(relProductSkuAttributeVO);
					} else {
						optionProduct.add(relProductSkuAttributeVO);
					}
					if (relProductSkuAttributeVO.getSkuItemId().equals(strategicSkuItemId)) {
						skuProductVO.setDisplayPrice(relProductSkuAttributeVO.getValue());
					}
				}
			}
			// 将基本信息租转的sku中
			addBaseInfo2Sku(byproduct, skuProductVO);
			skuProductVO.setRelProductSkuAttributeVOList(byproduct);
			skuProductCompareVO.setRelProductSkuAttributeVOList(optionProduct);

			//战略价格权限判断
			if ("1".equals(rolePrice.getIsShow())) {
				skuProductVO.setDisplayPrice("****");
			}

			List<SkuProductVO> skuProductVOs = new ArrayList<SkuProductVO>();
			String isProductCollection = skuProductVO.getIsProductCollection();
			if(isProductCollection.equals(IsProductCollection.YES.getValue())){
				String subset = skuProductVO.getSubset();
				if(StringUtils.isNotBlank(subset)){
					List<SkuProductVO> skuProductVOList = JSON.parseArray(subset, SkuProductVO.class);
					for(SkuProductVO sProductVO : skuProductVOList){
						SkuProduct product = skuProductMapper.selectByPrimaryKey(sProductVO.getProductId());
						if(product == null){
							return new Result<SkuProductCompareVO>(SkuResultCode.DATA_NOT_EXIST); 
						}
						SkuProductVO productVO = SkuProductConverter.toSkuProductVO(product);
						productVO.setNumber(sProductVO.getNumber());
						skuProductVOs.add(productVO);
					}
				}	
			}
			skuProductVO.setSkuProductVOs(skuProductVOs);
			products.add(skuProductVO);

			//计算部品案例库数量
			Integer caseStoreInNum = 0;
			Integer caseStoreOutNum = 0;
			List<CaseStoreInfo> caseStoreInfoList = caseStoreInfoMapper.selectByProductId(id);
			if (caseStoreInfoList != null && caseStoreInfoList.size() > 0) {
				for (CaseStoreInfo caseStoreInfo : caseStoreInfoList) {
					if ("绿城".equals(caseStoreInfo.getRealEstateCompany())) {
						caseStoreInNum++;
					} else {
						caseStoreOutNum++;
					}
				}
			}
			skuProductVO.setCaseStoreInNum(caseStoreInNum);
			skuProductVO.setCaseStoreOutNum(caseStoreOutNum);
		}
		skuProductCompareVO.setSkuProductVOs(products);

		// 产品固定信息
		SkuGroupVO baseSkuGroupVO = generateBaseSkuGroupVO(categoryId);
		skuProductCompareVO.addSkuGroupVO(baseSkuGroupVO);
		// 查询品类下面的skuGroup
		List<SkuGroup> skuGroups = skuGroupMapper.getByCategoryId(categoryId);
		// 查询组下面的sku
		for (SkuGroup skuGroup : skuGroups) {
			SkuGroupVO skuGroupVO = SkuGroupConverter.skuGroup2SkuGroupVO(skuGroup);

			List<SkuItem> bySkuGroup = skuItemMapper.getBySkuGroup(skuGroup.getId());
			skuGroupVO.setSkuItems(bySkuGroup);
			skuProductCompareVO.addSkuGroupVO(skuGroupVO);
		}

		//产品表头分类的判断
		Map<String, List<SkuItem>> groupMap = new LinkedHashMap<>();
		Map<Integer, String> groupNameMap = new LinkedHashMap<>();
		List<SkuGroup> baseSkuGroupList = skuGroupMapper.getByCategoryId(0);
		if (baseSkuGroupList != null && baseSkuGroupList.size() > 0) {
			for (SkuGroup skuGroup : baseSkuGroupList) {
				groupNameMap.put(skuGroup.getId(), skuGroup.getName());
			}
		}
		for (SkuItem skuItem : baseSkuGroupVO.getSkuItems()) {
			List<SkuItem> skuItemList;
			String skuGroupName = groupNameMap.get(skuItem.getSkuGroupId());
			if (groupMap.containsKey(skuGroupName)) {
				skuItemList = groupMap.get(skuGroupName);
			} else {
				skuItemList = new LinkedList<>();
			}
			skuItemList.add(skuItem);
			groupMap.put(groupNameMap.get(skuItem.getSkuGroupId()), skuItemList);
		}
		skuProductCompareVO.setGroupMap(groupMap);

		return new Result<SkuProductCompareVO>(skuProductCompareVO);
	}

	/**
	 * 生成基本信息组
	 * 
	 * @return
	 */
	private SkuGroupVO generateBaseSkuGroupVO(Integer categoryId) {
		// 基本信息组
		SkuGroupVO baseSkuGroupVO = new SkuGroupVO();
		baseSkuGroupVO.setCode("base");
		baseSkuGroupVO.setName("产品信息");

		List<SkuItem> skuItems = new ArrayList<>();

		// 名称
		SkuItem name = new SkuItem();
		name.setCode("name");
		name.setSkuName("产品名称");
		name.setSkuGroupId(1);
		skuItems.add(name);

		// 图片
		SkuItem photo = new SkuItem();
		photo.setCode("photo");
		photo.setSkuName("图片");
		photo.setSkuGroupId(1);
		skuItems.add(photo);

		// 价格
		SkuItem price = new SkuItem();
		price.setCode("price");
		price.setSkuName("工程市场价");
		price.setSkuGroupId(1);
		skuItems.add(price);

		// 品牌
		SkuItem brand = new SkuItem();
		brand.setCode("brand");
		brand.setSkuName("品牌");
		brand.setSkuGroupId(1);
		skuItems.add(brand);

		// 型号
		SkuItem model = new SkuItem();
		model.setCode("model");
		model.setSkuName("型号");
		model.setSkuGroupId(1);
		skuItems.add(model);

		// 产地
		SkuItem origin = new SkuItem();
		origin.setCode("origin");
		origin.setSkuName("产地");
		origin.setSkuGroupId(1);
		skuItems.add(origin);

		// 售后维保
		SkuItem maintenance = new SkuItem();
		maintenance.setCode("maintenance");
		maintenance.setSkuName("售后维保");
		maintenance.setSkuGroupId(1);
		skuItems.add(maintenance);

		List<SkuItem> baseSkuByCategoryId = skuItemMapper.getBaseSkuByCategoryId(categoryId);
		for (SkuItem skuItem : baseSkuByCategoryId) {
			if (!ItemValueType.MUILT_SELCT.getValue().equals(skuItem.getValueType()) && !ItemValueType.HIDDEN.getValue().equals(skuItem
					.getValueType())) {
				skuItems.add(skuItem);
			}
		}

		baseSkuGroupVO.setSkuItems(skuItems);
		return baseSkuGroupVO;
	}

	/**
	 * 将基本信息组装到sku中
	 * 
	 * @param byproduct
	 */
	private void addBaseInfo2Sku(List<RelProductSkuAttributeVO> byproduct, SkuProductVO skuProductVO) {

		RelProductSkuAttributeVO relProductSkuAttributeVO = new RelProductSkuAttributeVO();
		// 产品名称
		relProductSkuAttributeVO.setCode("name");
		relProductSkuAttributeVO.setValue(skuProductVO.getProductName());
		byproduct.add(relProductSkuAttributeVO);

		// 图片
		RelProductSkuAttributeVO relProductAkuAttributeVOPhoto = new RelProductSkuAttributeVO();
		relProductAkuAttributeVOPhoto.setCode("photo");
		relProductAkuAttributeVOPhoto.setValue(skuProductVO.getThumbnail());
		byproduct.add(relProductAkuAttributeVOPhoto);

		// 价格
		RelProductSkuAttributeVO relProductAkuAttributeVOPrice = new RelProductSkuAttributeVO();
		relProductAkuAttributeVOPrice.setCode("price");
		relProductAkuAttributeVOPrice.setValue(String.valueOf(skuProductVO.getPrice()));
		byproduct.add(relProductAkuAttributeVOPrice);

		// 品牌
		RelProductSkuAttributeVO relProductAkuAttributeVOBrand = new RelProductSkuAttributeVO();
		relProductAkuAttributeVOBrand.setCode("brand");
		Brand brand = brandMapper.selectByPrimaryKey(skuProductVO.getSkuBrandId());
		String brandStr = null == brand ? "" : brand.getLabel();
		relProductAkuAttributeVOBrand.setValue(brandStr);
		byproduct.add(relProductAkuAttributeVOBrand);

		// 型号
		RelProductSkuAttributeVO relProductAkuAttributeVOModel = new RelProductSkuAttributeVO();
		relProductAkuAttributeVOModel.setCode("model");
		relProductAkuAttributeVOModel.setValue(skuProductVO.getModel());
		byproduct.add(relProductAkuAttributeVOModel);

		// 产地
		RelProductSkuAttributeVO relProductAkuAttributeVOOrigin = new RelProductSkuAttributeVO();
		relProductAkuAttributeVOOrigin.setCode("origin");
		relProductAkuAttributeVOOrigin.setValue(skuProductVO.getAddress());
		byproduct.add(relProductAkuAttributeVOOrigin);

		// 售后维保
		RelProductSkuAttributeVO relProductAkuAttributeVOMaintenance = new RelProductSkuAttributeVO();
		relProductAkuAttributeVOMaintenance.setCode("maintenance");
		relProductAkuAttributeVOMaintenance.setValue(skuProductVO.getSalesMaintenance());
		byproduct.add(relProductAkuAttributeVOMaintenance);
	}

	@Override
	public Result<String> save(MongoSkuProductVO productVO) {
		mongoTemplate.save(productVO, SKU_PRODUCT_COLLECTION);
		return new Result<String>(SkuResultCode.SUCCESS, true);
	}

	@Override
	public Result<PageModel<SkuProductVO>> pageQueryProduct(SkuProductQueryVO skuProductQueryVO,
			PageModel<SkuProductVO> pageModel) {
		if (skuProductQueryVO == null || pageModel == null) {
			return new Result<PageModel<SkuProductVO>>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}

		// 验证数据完整性
		Set<ConstraintViolation<SkuProductQueryVO>> errors = validator.validate(skuProductQueryVO,
				SkuProductQueryVO.Base.class);
		if (!errors.isEmpty()) {
			StringBuilder errorMsg = new StringBuilder();
			for (ConstraintViolation<SkuProductQueryVO> error : errors) {
				LOGGER.warn("illegal parameter, path: {}, message: {}", error.getPropertyPath(), error.getMessage());
				errorMsg.append(error.getMessage());
			}
			return new Result<>(SkuResultCode.DATA_ERROR, errorMsg.toString());
		}

		BasicDBObject searchCond = new BasicDBObject();
		BasicDBList condList = new BasicDBList();
		Query query = new Query();
		// 品类必填
		condList.add(new BasicDBObject("skuCategoryId", skuProductQueryVO.getSkuCategoryId()));
		query.addCriteria(Criteria.where("skuCategoryId").is(skuProductQueryVO.getSkuCategoryId()));
		condList.add(new BasicDBObject("auditStatus", skuProductQueryVO.getAuditStatus()));
		query.addCriteria(Criteria.where("auditStatus").is(skuProductQueryVO.getAuditStatus()));
		condList.add(new BasicDBObject("isDeleted", IsDeleted.NO.getValue()));
		query.addCriteria(Criteria.where("isDeleted").is(IsDeleted.NO.getValue()));
		if(StringUtils.isNotBlank(skuProductQueryVO.getIsProductCollection())){
			condList.add(new BasicDBObject("isProductCollection", skuProductQueryVO.getIsProductCollection()));
			query.addCriteria(Criteria.where("isProductCollection").is(skuProductQueryVO.getIsProductCollection()));
		}

		if (skuProductQueryVO.getSkuBrandId() != null) {
			condList.add(new BasicDBObject("skuBrandId", skuProductQueryVO.getSkuBrandId()));
			query.addCriteria(Criteria.where("skuBrandId").is(skuProductQueryVO.getSkuBrandId()));
		}else{
			BasicDBList brandId = new BasicDBList();
			List<Integer> brands = skuProductQueryVO.getBrandIds();
			if(brands != null && brands.size()>0){
				for(Integer bId:brands){
					brandId.add(bId);
				}
				searchCond.put("skuBrandId", new BasicDBObject("$in",brandId));
				query.addCriteria(Criteria.where("skuBrandId").in(skuProductQueryVO.getBrandIds()));
			}	
		}
		
		if (StringUtils.isNotEmpty(skuProductQueryVO.getProductName())) {
			Pattern pattern = Pattern.compile("^.*" + skuProductQueryVO.getProductName() + ".*$", Pattern.CASE_INSENSITIVE);
			condList.add(new BasicDBObject("productName", pattern));
			query.addCriteria(Criteria.where("productName").regex(pattern));
		}
		
		Criteria operateTimeCri = Criteria.where("price");
		if (skuProductQueryVO.getPriceStart() != null) {
			BasicDBObject queryCondition = new BasicDBObject();
			BigDecimal priceStart = skuProductQueryVO.getPriceStart();
			queryCondition.put("price", new BasicDBObject("$gte", priceStart.floatValue()));
			condList.add(queryCondition);
			operateTimeCri.gte(priceStart.floatValue());
			
		}
		
		if (skuProductQueryVO.getPriceEnd() != null) {
			BasicDBObject queryCondition = new BasicDBObject();
			BigDecimal priceEnd = skuProductQueryVO.getPriceEnd();
			
			queryCondition.put("price", new BasicDBObject("$lte", priceEnd.floatValue()));
			condList.add(queryCondition);
			operateTimeCri.lte(priceEnd.floatValue());
		}
		
		if (skuProductQueryVO.getPriceStart() != null || skuProductQueryVO.getPriceEnd() != null) {
			query.addCriteria(operateTimeCri);
		}
	

		if (skuProductQueryVO.getSkuItemAttributeVOs() != null) {
			for (Iterator<SkuItemAttributeVO> iter = skuProductQueryVO.getSkuItemAttributeVOs().iterator(); iter
					.hasNext();) {
				SkuItemAttributeVO skuItemAttributeVO = iter.next();
				condList.add(new BasicDBObject("skus." + skuItemAttributeVO.getSkuItemId() + ".skuItemId",
						skuItemAttributeVO.getSkuItemId()));
				condList.add(new BasicDBObject("skus." + skuItemAttributeVO.getSkuItemId() + ".value",
						skuItemAttributeVO.getValue()));
				query.addCriteria(Criteria.where("skus." + skuItemAttributeVO.getSkuItemId() + ".skuItemId")
						.is(skuItemAttributeVO.getSkuItemId()))
						.addCriteria(Criteria.where("skus." + skuItemAttributeVO.getSkuItemId() + ".value")
								.is(skuItemAttributeVO.getValue()));
			}
		}

		int totalCounter = (int) mongoTemplate.count(query, SKU_PRODUCT_COLLECTION);
		if (totalCounter == 0) {
			return new Result<PageModel<SkuProductVO>>(SkuResultCode.DATA_NOT_EXIST);
		}

		pageModel.setTotalCount(totalCounter);
		
		
		searchCond.put("$and", condList);

		//查询需要同步的旧数据
		DBCursor limitSyn = mongoTemplate.getCollection(SKU_PRODUCT_COLLECTION).find(searchCond)
				.sort(new BasicDBObject("gmtCreated", -1)).skip((pageModel.getPageNo() - 1) * pageModel.getPageSize())
				.limit(pageModel.getPageSize());
		while (limitSyn.hasNext()) {
			synStrategicPrice(limitSyn.next());
		}

		DBCursor limit = mongoTemplate.getCollection(SKU_PRODUCT_COLLECTION).find(searchCond)
				.sort(new BasicDBObject("gmtCreated", -1)).skip((pageModel.getPageNo() - 1) * pageModel.getPageSize())
				.limit(pageModel.getPageSize());
		List<SkuProductVO> skuProductVOs = new ArrayList<SkuProductVO>(pageModel.getPageSize());
		while (limit.hasNext()) {
			SkuProductVO skuProductVO = bsonMapToObj(limit.next());
			skuProductVOs.add(skuProductVO);
		}

		pageModel.setPagedRecords(skuProductVOs);
		return new Result<PageModel<SkuProductVO>>(pageModel);
	}

	/**
	 * 同步战略报价
	 *
	 * @param dbObject
	 */
	private void synStrategicPrice(DBObject dbObject) {
		@SuppressWarnings("rawtypes")
		Map map = dbObject.toMap();
		Double strategicPriceDoub = (Double) map.get("strategicPrice");
		if (strategicPriceDoub == null) {
			Integer skuCategoryId = (Integer) map.get("skuCategoryId");
			Integer productId = (Integer) map.get("productId");
			Result<Integer> strategicSkuItemIdRes = skuItemManager.getStrategicSkuItemId(skuCategoryId);
			Integer strategicSkuItemId = null;
			if (strategicSkuItemIdRes.isSuccess()) {
				strategicSkuItemId = strategicSkuItemIdRes.getDataModel();
			}
			if (strategicSkuItemId != null) {
				RelProductSkuAttribute relProductSkuAttribute = relProductSkuAttributeMapper.selectByProductIdAndSkuItemId
						(productId, strategicSkuItemId);
				if (relProductSkuAttribute != null) {
					try {
						Query query1 = new Query(Criteria.where("productId").is(productId));
						Update update = Update.update("strategicPrice", Double.valueOf(relProductSkuAttribute.getValue()));
						mongoTemplate.updateMulti(query1, update, MongoSkuProductVO.class, SKU_PRODUCT_COLLECTION);
					} catch (Exception e) {
						LOGGER.error("部品列表同步战略报价出错,productId=" + productId);
					}
				}
			}
		}
	}

	/**
	 * 将bson的map转化为对象
	 * 
	 * @param dbObject
	 * @return
	 */
	private SkuProductVO bsonMapToObj(DBObject dbObject) {
		SkuProductVO skuProductVO = new SkuProductVO();
		@SuppressWarnings("rawtypes")
		Map map = dbObject.toMap();
		skuProductVO.setSkuCategoryId((Integer) map.remove("skuCategoryId"));
		skuProductVO.setProductId((Integer) map.remove("productId"));
		skuProductVO.setProductName((String) map.remove("productName"));
		skuProductVO.setThumbnail((String) map.remove("thumbnail"));
		Double priceStr = (Double) map.remove("price");
		if (priceStr != null) {
			BigDecimal price = new BigDecimal(priceStr).setScale(2,
					BigDecimal.ROUND_HALF_UP);
			skuProductVO.setPrice(price);
		}
		skuProductVO.setAddress((String) map.remove("address"));
		skuProductVO.setAuditStatus((String) map.remove("auditStatus"));
		skuProductVO.setGmtCreated((Date) map.remove("gmtCreated"));
		skuProductVO.setGmtModified((Date) map.remove("gmtModified"));
		skuProductVO.setPicturePath((String) map.remove("picturePath"));
		skuProductVO.setProductCode((String) map.remove("productCode"));
		skuProductVO.setPicturePathType((String) map.remove("picturePathType"));
		skuProductVO.setCompanyName((String) map.remove("companyName"));
		skuProductVO.setBrandName((String) map.remove("brandName"));
		skuProductVO.setModel((String) map.remove("model"));
		skuProductVO.setIsProductCollection((String) map.remove("isProductCollection"));
		Double strategicPriceDoub = (Double) map.remove("strategicPrice");
		if (strategicPriceDoub != null) {
			BigDecimal strategicPrice = new BigDecimal(strategicPriceDoub).setScale(2,
					BigDecimal.ROUND_HALF_UP);
			skuProductVO.setStrategicPrice(strategicPrice);
		}

		return skuProductVO;
	}

	@Override
	public Result<String> saveUploadedFileUpdate(MultipartFile uploadedFile) {
		CommonsMultipartFile cf = (CommonsMultipartFile) uploadedFile;
		DiskFileItem fi = (DiskFileItem) cf.getFileItem();
		File f = fi.getStoreLocation();
		LinkedMultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
		FileSystemResource resource = new FileSystemResource(f);
		if (fi.isInMemory()) {
			try {
				OutputStream out = new FileOutputStream(f);
				try {
					out.write(fi.get());
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		param.add("application/json", "UTF-8");
		param.add("file", resource);
		String fileName = null;
		try {
			fileName = URLEncoder.encode(uploadedFile.getOriginalFilename(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		param.add("fileName", fileName);
		Map<String, Object> additional = new HashMap<>();
		additional.put("boss", "boss");
		JSONObject jsonObject = new JSONObject(additional);
		param.add("additional", jsonObject.toJSONString());
		param.add("fileType", uploadedFile.getContentType());
		String fileKey = restTemplate.postForObject(restfulUrl + "doUpload", param, String.class);
		if (StringUtils.isBlank(fileKey))
			return new Result<String>(SkuResultCode.SYS_EXCEPTION);
		return new Result<String>(fileKey);
	}
	
	@Override
	public Result<String> uploadedFileUpdate(File file,String type) {
		LinkedMultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
		FileSystemResource resource = new FileSystemResource(file);
	
		param.add("application/json", "UTF-8");
		param.add("file", resource);
		String fileName = null;
		String fileKey = "";
		try {
			fileName = URLEncoder.encode(file.getName(), "UTF-8");
			param.add("fileName", fileName);
			Map<String, Object> additional = new HashMap<>();
			additional.put("boss", "boss");
			JSONObject jsonObject = new JSONObject(additional);
			param.add("additional", jsonObject.toJSONString());
			param.add("fileType", type);
			fileKey = restTemplate.postForObject(restfulUrl + "doUpload", param, String.class);
			if (StringUtils.isBlank(fileKey))
				return new Result<String>(SkuResultCode.SYS_EXCEPTION);
		} catch (Exception e) {
			LOGGER.error("exception {}",e);
		}
		
		return new Result<String>(fileKey);
	}


	@Override
	public Result<List<SkuProduct>> selectAllProduct() {
		List<SkuProduct> skuProducts = skuProductMapper.selectAllProduct();

		return new Result<List<SkuProduct>>(skuProducts);
	}

	@Override
	public Result<List<RelProductSkuAttribute>> selectByProductId(Integer productId) {
		List<RelProductSkuAttribute> relProductAkuAttributeWithSkuCodes = relProductSkuAttributeMapper
				.selectByProductId(productId);

		return new Result<List<RelProductSkuAttribute>>(relProductAkuAttributeWithSkuCodes);
	}

	/**
	 * 查询产品详情 shenpingfeng 
	 * 2016年12月1日
	 * @param productId
	 * @return
	 */
	@Override
	public Result<SkuProductDetailVO> findProductDetailByProdcutId(Integer productId, HttpServletResponse response) {
		SkuProduct skuProduct = skuProductMapper.selectByPrimaryKey(productId);
		if (skuProduct == null) {
			return new Result<SkuProductDetailVO>(SkuResultCode.DATA_NOT_EXIST);
		}
		SkuProductVO skuProductVO = SkuProductConverter.toSkuProductVO(skuProduct);

		//查询公司信息
		Integer companyId = skuProduct.getCompanyId();

		Result<SkuCompanyVO> skuCompanyResult = skuCompanyManager.findSkuCompanyByCompanyId(companyId);
		SkuCompanyVO skuCompanyVO = skuCompanyResult.getDataModel();

		//查询产品图片
		Result<List<ProductPictureVO>> resultProductPidcture = productPictureManager
				.findProductPictureByProductId(productId);
		List<ProductPictureVO> productPictureVOs = resultProductPidcture.getDataModel();

		//查询产品sku属性关联
		List<RelProductSkuAttribute> relProductAkuAttributes = relProductSkuAttributeMapper
				.selectByProductId(productId);
		Map<String, RelProductSkuAttribute> skus = new LinkedHashMap<String, RelProductSkuAttribute>();
		List<RelProductSkuAttributeVO> optionSkus = new LinkedList<>();
		for (RelProductSkuAttribute rel : relProductAkuAttributes) {
			SkuItem skuItem = skuItemMapper.selectByPrimaryKey(rel.getSkuItemId());
			if(skuItem!=null) {
				if (!ItemValueType.MUILT_SELCT.getValue().equals(skuItem.getValueType())) {
					skus.put(skuItem.getSkuName(), rel);
				} else {
					RelProductSkuAttributeVO relProductSkuAttributeVO = new RelProductSkuAttributeVO();
					BeanUtils.copyProperties(rel, relProductSkuAttributeVO);
					relProductSkuAttributeVO.setSkuItemName(skuItem.getSkuName());
					optionSkus.add(relProductSkuAttributeVO);
				}
			}
		}
		skuProductVO.setRelProductAkuAttributes(skus);

		//查询品类
		Result<Category> categoryResult = categoryManager.getCagegorysById(skuProductVO.getSkuCategoryId());
		Category category = categoryResult.getDataModel();
		Integer parentId = category.getParentId();
		Result<List<Category>> resultCategories = categoryManager.getCagegorysByParentId(parentId);
		List<Category> categories = resultCategories.getDataModel();
		List<Category> categoryList = new ArrayList<Category>();
		categoryList.add(category);
		categoryList.addAll(categories);

		//查询品牌
		BrandVO brandVO = brandMapper.selectByCategoryIdAndBrandId(skuProductVO.getSkuCategoryId(), skuProductVO.getSkuBrandId
				());
		//查询获取品类品牌属性值
		List<CategoryBrandAssoVO> categoryBrandAssoVOList = getCategoryBrandAssoVOList(skuProductVO.getSkuCategoryId(), brandVO
				.getCategoryBrandId());
		brandVO.setCategoryBrandAssoVOList(categoryBrandAssoVOList);
		//查询获取品类品牌运费调差值
		List<CategoryBrandRegionVO> categoryBrandRegionVOList = categoryBrandBusiUtil.getCategoryBrandRegionVOList(brandVO
				.getCategoryBrandId());
		brandVO.setCategoryBrandRegionVOList(categoryBrandRegionVOList);

		//查询子品类
		List<SkuProductVO> skuProductVOs = new ArrayList<SkuProductVO>();
		String isProductCollection = skuProductVO.getIsProductCollection();
		if(isProductCollection.equals(IsProductCollection.YES.getValue())){
			String subset = skuProductVO.getSubset();
			if(StringUtils.isNotBlank(subset)){
				List<SkuProductVO> skuProductVOList = JSON.parseArray(subset, SkuProductVO.class);
				for(SkuProductVO sProductVO : skuProductVOList){
					SkuProduct product = skuProductMapper.selectByPrimaryKey(sProductVO.getProductId());
					if(product == null){
						return new Result<SkuProductDetailVO>(SkuResultCode.DATA_NOT_EXIST); 
					}
					SkuProductVO productVO = SkuProductConverter.toSkuProductVO(product);
					//查询品牌
					Brand brand = brandMapper.selectByPrimaryKey(productVO.getSkuBrandId());
					BrandVO brandVO2 = BrandConverter.toBrandVO(brand);
					productVO.setNumber(sProductVO.getNumber());
					productVO.setBrandVO(brandVO2);
					skuProductVOs.add(productVO);
				}
			}	
		}	
		skuProductVO.setSkuProductVOs(skuProductVOs);
		SkuProductDetailVO skuProductDetailVO = new SkuProductDetailVO();
		skuProductDetailVO.setProductPictureVOs(productPictureVOs);
		skuProductDetailVO.setSkuCompanyVO(skuCompanyVO);
		skuProductDetailVO.setSkuProductVO(skuProductVO);
		skuProductDetailVO.setCategory(category);
		skuProductDetailVO.setBrandVO(brandVO);
		skuProductDetailVO.setCategories(categoryList);
		skuProductDetailVO.setRelProductSkuAttributeVOList(optionSkus);

		return new Result<SkuProductDetailVO>(skuProductDetailVO);
	}

	@Override
	public Result<File> loadUploadedFileUpdate(String filePath, HttpServletResponse response) {
		if (filePath == null) {
			return new Result<File>(SkuResultCode.DATA_ERROR);
		}

		File file = new File(filePath);
		if (!file.exists()) {
			LOGGER.info("磁盘上未找到filepath为{}的文件", filePath);

			Boolean doCheckAttachment = doCheckAttachment(filePath, response);
			if (!doCheckAttachment) {
				LOGGER.error("阿里云上未找到key为{}的文件", filePath);
				return new Result<File>(SkuResultCode.DATA_NOT_EXIST);
			}
		} else {
			writeFileToResponseInline(file, response);
		}

		return new Result<File>(file);
	}

	/**
	 * 品类品牌属性值
	 *
	 * @param categoryId 品类id
	 * @param categoryBrandId 品类品牌关联表id
	 * @return List<CategoryBrandAssoVO>
	 */
	private List<CategoryBrandAssoVO> getCategoryBrandAssoVOList(Integer categoryId, Integer categoryBrandId) {
		List<CategoryBrandAssoVO> categoryBrandAssoVOList = new LinkedList<>();

		List<SkuItem> skuItemList = skuItemMapper.selectByCategoryIdAndValueType(categoryId, ItemValueType.HIDDEN.getValue());
		List<Integer> skuItemIdList = new LinkedList<>();
		Map<Integer, List<CategoryBrandAssoVO>> categoryBrandVOMap = new LinkedHashMap<>();
		if (skuItemList != null && skuItemList.size() > 0) {
			Map<Integer, String> skuItemNameMap = new LinkedHashMap<>();
			for (SkuItem skuItem : skuItemList) {
				skuItemIdList.add(skuItem.getId());
				skuItemNameMap.put(skuItem.getId(), skuItem.getSkuName());
			}

			List<CategoryBrandAssociate> categoryBrandAssociateList = categoryBrandAssociateMapper
					.selectByCategoryBrandIdAndItemIds(categoryBrandId, skuItemIdList);
			Map<Integer, CategoryBrandAssociate> categoryBrandAssoMap = new LinkedHashMap<>();
			if (categoryBrandAssociateList != null && categoryBrandAssociateList.size() > 0) {
				for (CategoryBrandAssociate categoryBrandAssociate : categoryBrandAssociateList) {
					categoryBrandAssoMap.put(categoryBrandAssociate.getSkuItemId(), categoryBrandAssociate);
				}
			}

			categoryBrandAssoVOList = categoryBrandBusiUtil.getCategoryBrandAssoVOListByItem(skuItemNameMap,
					categoryBrandAssoMap);
		}

		return categoryBrandAssoVOList;
	}

	/**
	 * 获取部品详情页品类品牌属性值映射
	 * @param categoryBrandAssoVOList 品类品牌属性值
	 * @return Map<String, Object>
	 */
	private Map<String, Object> getCategoryBrandAssoMap(List<CategoryBrandAssoVO> categoryBrandAssoVOList) {
		Map<String, Object> resultMap = new LinkedHashMap<>();
		if (categoryBrandAssoVOList != null && categoryBrandAssoVOList.size() > 0) {
			for (CategoryBrandAssoVO categoryBrandAssoVO : categoryBrandAssoVOList) {
				List<CategoryBrandDetailVO> categoryBrandDetailVOList;
				CategoryBrandDetailVO categoryBrandDetailVO = new CategoryBrandDetailVO();
				if (categoryBrandAssoVO.getSkuItemName().contains("悬浮安装") || categoryBrandAssoVO.getSkuItemName().contains
						("施胶安装")) {
					categoryBrandDetailVO.setSkuItemName(categoryBrandAssoVO.getSkuItemName());
					categoryBrandDetailVO.setAttrValue(categoryBrandAssoVO.getAttrValue());
					for (CategoryBrandAssoVO categoryBrandAssoVO1 : categoryBrandAssoVOList) {
						if (categoryBrandAssoVO.getSkuItemName().contains("工字铺") && "安装损耗率（%）-工字铺".equals
								(categoryBrandAssoVO1.getSkuItemName())) {
							categoryBrandDetailVO.setInfoValue(categoryBrandAssoVO1.getAttrValue());
						}
						if (categoryBrandAssoVO.getSkuItemName().contains("人字拼") && "安装损耗率（%）-人字拼".equals
								(categoryBrandAssoVO1.getSkuItemName())) {
							categoryBrandDetailVO.setInfoValue(categoryBrandAssoVO1.getAttrValue());
						}
					}
					if (resultMap.containsKey("安裝方式")) {
						categoryBrandDetailVOList = (List<CategoryBrandDetailVO>) resultMap.get("安裝方式");
					} else {
						categoryBrandDetailVOList = new LinkedList<>();
					}
					categoryBrandDetailVOList.add(categoryBrandDetailVO);
					resultMap.put("安裝方式", categoryBrandDetailVOList);
				}
				if (categoryBrandAssoVO.getSkuItemName().contains("安装损耗率")) {
					categoryBrandDetailVO.setSkuItemName(categoryBrandAssoVO.getSkuItemName().split("-")[1]);
					if (resultMap.containsKey("安装损耗率")) {
						categoryBrandDetailVOList = (List<CategoryBrandDetailVO>) resultMap.get("安装损耗率");
					} else {
						categoryBrandDetailVOList = new LinkedList<>();
					}
					categoryBrandDetailVOList.add(categoryBrandDetailVO);
					resultMap.put("安装损耗率", categoryBrandDetailVOList);
				}
				if (categoryBrandAssoVO.getSkuItemName().contains("成品保护费")) {
					categoryBrandDetailVO.setSkuItemName(categoryBrandAssoVO.getSkuItemName().split("-")[1]);
					categoryBrandDetailVO.setAttrValue(categoryBrandAssoVO.getAttrValue());
					if (resultMap.containsKey("成品保护费")) {
						categoryBrandDetailVOList = (List<CategoryBrandDetailVO>) resultMap.get("成品保护费");
					} else {
						categoryBrandDetailVOList = new LinkedList<>();
					}
					categoryBrandDetailVOList.add(categoryBrandDetailVO);
					resultMap.put("成品保护费", categoryBrandDetailVOList);
				}
			}
		}
		return resultMap;
	}

	private Boolean doCheckAttachment(@RequestParam(value = "key", required = true) String key,
			HttpServletResponse response) {
		if (StringUtils.isBlank(key)) {
			LOGGER.info("the parameter key is null");
			return false;
		}
		// 校验是否有该文件
		String jsonFileInfo = restTemplate.getForObject(restfulUrl + "doQuery?key=" + key, String.class);
		if (jsonFileInfo == null) {
			LOGGER.info("query no compareble file with this key {} ", key);
			return false;
		}
		try {
			final RequestCallback requestCallback = new RequestCallback() {
				@Override
				public void doWithRequest(final ClientHttpRequest request) throws IOException {
					LOGGER.info("=========request begin=========");
				}
			};
			final OutputStream out = response.getOutputStream();
			setResponseInfo(jsonFileInfo, response);
			final ResponseExtractor<Object> responseExtractor = new ResponseExtractor<Object>() {
				@Override
				public Object extractData(ClientHttpResponse response) throws IOException {
					LOGGER.info("=========response begin=========");
					InputStream in = response.getBody();
					IOUtils.copy(in, out);
					return false;
				}
			};

			restTemplate.execute(restfulUrl + "doCheck?key=" + key, HttpMethod.GET, requestCallback, responseExtractor);
			return true;
		} catch (Exception e) {
			LOGGER.error("error maybe e: {}", e.toString());
			return false;
		}
	}

	private void setResponseInfo(String jsonFileInfo, HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		response.setContentType((String) findFileAttr(jsonFileInfo, "fileType"));
		String fileName = (String) findFileAttr(jsonFileInfo, "fileName");
		LOGGER.info("the fileName is {}", fileName);
		String encodeFileName = null;
		try {
			encodeFileName = URLEncoder.encode(fileName, "UTF-8");
		} catch (Exception e) {
			LOGGER.error("encode this fileName {} caught this error e: {}", fileName, e.toString());
		}
		response.setHeader("Content-Disposition", "inline;fileName=" + encodeFileName);
	}

	private Object findFileAttr(String json, String attr) {
		JSONObject jsonObject = JSONObject.parseObject(json);
		return jsonObject.get(attr);
	}

	public static void writeFileToResponseInline(File file, HttpServletResponse response) {

		if (file == null || !file.exists()) {
			LOGGER.error("illegal parameter. file is not exist.");
			return;
		}

		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-Disposition", "inline;fileName=" + file.getName());

		InputStream inputStream = null;
		OutputStream os = null;
		try {
			inputStream = new FileInputStream(file);
			os = response.getOutputStream();
			byte[] b = new byte[2048];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			os.flush();
		} catch (Exception e) {
			LOGGER.error("exception.", e);
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				LOGGER.error("ignore.", e);
			}
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				LOGGER.error("ignore.", e);
			}
		}
	}

	/**
	 * 创建产品
	 * shenpingfeng 2016年12月5日
	 * @param skuProductVO
	 * @return
	 */
	@Override
	public Result<String> createSkuProduct(SkuProductVO skuProductVO) {

		SkuProduct skuProduct = SkuProductConverter.toSkuProduct(skuProductVO);
		UUID randomUUID = UUID.randomUUID();
		String productCode = randomUUID.toString();
		skuProduct.setProductCode(productCode);
		skuProduct.setIsDeleted(IsDeleted.NO.getValue());
		skuProduct.setGmtCreated(new Date());
		skuProduct.setGmtModified(new Date());
		skuProduct.setAuditStatus(AuditStatus.AUDIT.getValue());
		skuProduct.setThumbnail(skuProductVO.getPicturePath());
		skuProduct.setPicturePathType(PicturePathType.RELATIVE_PATH.getValue());
		if (StringUtils.isBlank(skuProduct.getIsCustomizable())) {
			skuProduct.setIsCustomizable("0");
		}

		int row = skuProductMapper.insertSelective(skuProduct);
		if (row == 0) {
			return new Result<String>(SkuResultCode.ADD_FAIL);
		}

		return new Result<String>(skuProduct.getProductCode());
	}

	/**
	 * 根据productCode查询 shenpingfeng 
	 * 2016年12月5日
	 * @param productCode
	 * @return
	 */
	@Override
	public Result<SkuProductVO> findProductByProductCode(String productCode) {
		if (StringUtils.isBlank(productCode)) {
			return new Result<SkuProductVO>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		SkuProduct skuProduct = skuProductMapper.selectProductByProductCode(productCode);
		if (skuProduct == null) {
			return new Result<SkuProductVO>(SkuResultCode.DATA_NOT_EXIST);
		}
		SkuProductVO skuProductVO = SkuProductConverter.toSkuProductVO(skuProduct);

		return new Result<SkuProductVO>(skuProductVO);
	}

	/**
	 * 更新产品信息 shenpingfeng 
	 * 2016年12月5日
	 * @param skuProductVO
	 * @return
	 */
	@Override
	public Result<String> updateSkuProduct(SkuProductVO skuProductVO) {

		SkuProduct skuProduct = SkuProductConverter.toSkuProduct(skuProductVO);
		skuProduct.setGmtModified(new Date());

		int row = skuProductMapper.updateByPrimaryKeySelective(skuProduct);
		if (row == 0) {
			return new Result<String>(SkuResultCode.UPDATE_FAIL);
		}

		return new Result<String>(skuProduct.getProductCode());
	}

	/**
	 * 根据productId查询
	 * shenpingfeng
	 * 2016年12月22日
	 * @param productId
	 * @return
	 */
	@Override
	public Result<SkuProduct> findByProductId(Integer productId) {

		if (productId == null) {
			return new Result<>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		SkuProduct skuProduct = skuProductMapper.selectByPrimaryKey(productId);
		if (skuProduct == null) {
			return new Result<SkuProduct>(SkuResultCode.DATA_NOT_EXIST);
		}

		return new Result<SkuProduct>(skuProduct);
	}

	@Override
	public Result<String> deleteProductByMongoDB(Integer productId) {
		if (productId == null) {
			return new Result<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		mongoTemplate.getCollection(SKU_PRODUCT_COLLECTION).remove(new BasicDBObject("productId", productId));

		return new Result<String>(productId.toString());
	}

	/**
	 * 创建product sku属性
	 * shenpingfeng
	 * 2016年12月7日
	 * @param relProductAkuAttribute
	 * @return
	 */
	@Override
	public Result<String> createProductSkuAttribute(RelProductSkuAttribute relProductAkuAttribute) {
		if (relProductAkuAttribute == null) {
			return new Result<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		relProductAkuAttribute.setIsDeleted(IsDeleted.NO.getValue());
		relProductAkuAttribute.setGmtCreated(new Date());
		relProductAkuAttribute.setGmtModified(new Date());
		int row = relProductSkuAttributeMapper.insertSelective(relProductAkuAttribute);
		if (row == 0) {
			return new Result<String>(SkuResultCode.ADD_FAIL);
		}
		return new Result<String>(relProductAkuAttribute.getValue());
	}

	/**
	 * 更新
	 * shenpingfeng
	 * 2016年12月7日
	 * @param relProductskuAttribute
	 * @return
	 */
	@Override
	public Result<String> updateProductSkuAttribute(RelProductSkuAttribute relProductskuAttribute) {
		if (relProductskuAttribute.getId() == null) {
			return new Result<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		relProductskuAttribute.setGmtModified(new Date());
		int row = relProductSkuAttributeMapper.updateByPrimaryKeySelective(relProductskuAttribute);
		if (row == 0) {
			return new Result<String>(SkuResultCode.UPDATE_FAIL);
		}
		return new Result<String>(relProductskuAttribute.getValue());
	}
	/**
	 * 根据productId和skuItemId查询
	 * shenpingfeng
	 * 2016年12月7日
	 * @param productId
	 * @param skuItemId
	 * @return
	 */
	@Override
	public Result<RelProductSkuAttribute> findProductSkuAttributeByProductIdAndSkuItemId(Integer productId,
			Integer skuItemId) {
		if (productId == null || skuItemId == null) {
			return new Result<RelProductSkuAttribute>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}

		RelProductSkuAttribute relProductAkuAttribute = relProductSkuAttributeMapper
				.selectByProductIdAndSkuItemId(productId, skuItemId);
		if (relProductAkuAttribute == null) {
			return new Result<RelProductSkuAttribute>(SkuResultCode.DATA_NOT_EXIST);
		}
		return new Result<RelProductSkuAttribute>(relProductAkuAttribute);
	}
	
	/**
	 * 删除
	 * shenpingfeng
	 * 2016年12月14日
	 * @param skuProduct
	 * @return
	 */
	@Override
	public Result<String> deleteSkuProduct(SkuProduct skuProduct) {
		if (skuProduct == null || skuProduct.getProductId() == null) {
			return new Result<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		skuProduct.setIsDeleted(IsDeleted.YES.getValue());

		int row = skuProductMapper.updateByPrimaryKeySelective(skuProduct);
		if(row == 0){
			return new Result<String>(SkuResultCode.DELETE_FAIL);
		}
		mongoTemplate.getCollection(SKU_PRODUCT_COLLECTION).remove(new BasicDBObject("productId", skuProduct.getProductId()));

		return new Result<String>(row+"");
	}
	
	/**
	 * 根据skuCategoryId和skuBrandId查询产品
	 * shenpingfeng
	 * 2017年2月16日
	 * @param skuCategoryId
	 * @param skuBrandId
	 * @return
	 */
	@Override
	public Result<List<SkuProductVO>> findProductBySkuCategoryIdAndSkuBrandId(Integer skuCategoryId,Integer skuBrandId) {
		if (skuCategoryId == null || skuBrandId == null) {
			return new Result<List<SkuProductVO>>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		List<SkuProduct> skuProducts = skuProductMapper.selectProductBySkuCategoryIdAndSkuBrandId(skuCategoryId, skuBrandId);
		if(skuProducts == null || skuProducts.size() == 0){
			return new Result<List<SkuProductVO>>(SkuResultCode.DATA_NOT_EXIST);
		}
		List<SkuProductVO> skuProductVOs = SkuProductConverter.toSkuProductVOs(skuProducts);
		
		return new Result<List<SkuProductVO>>(skuProductVOs);
	}
	
	/**
	 * mongodb更新
	 * shenpingfeng
	 * 2017年2月10日
	 * @param skuProduct
	 * @return
	 */
	@Override
	public Result<String> updateSkuProduct(MongoSkuProductVO skuProduct) {
		if (skuProduct == null || skuProduct.getProductId() == null) {
			return new Result<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		Update update = new Update();
		if(StringUtils.isNotEmpty(skuProduct.getProductName())){
			update.set("productName", skuProduct.getProductName());
		}
		if(StringUtils.isNotEmpty(skuProduct.getProductCode())){
			update.set("productCode", skuProduct.getProductCode());
		}
		if(StringUtils.isNotEmpty(skuProduct.getDescription())){
			update.set("description", skuProduct.getDescription());
		}
		if(StringUtils.isNotEmpty(skuProduct.getPicturePath())){
			update.set("picturePath", skuProduct.getPicturePath());
		}
		if(StringUtils.isNotEmpty(skuProduct.getThumbnail())){
			update.set("thumbnail", skuProduct.getThumbnail());
		}
		if(StringUtils.isNotEmpty(skuProduct.getAuditStatus())){
			update.set("auditStatus", skuProduct.getAuditStatus());
		}
		if(skuProduct.getSkuBrandId() != null){
			update.set("skuBrandId", skuProduct.getSkuBrandId());
		}
		if(skuProduct.getSkuCategoryId() != null){
			update.set("skuCategoryId", skuProduct.getSkuCategoryId());
		}
		if(skuProduct.getPrice() != null){
			update.set("price", skuProduct.getPrice());		
		}
		if(skuProduct.getAddress() != null){
			update.set("address", skuProduct.getAddress());
		}
		if(skuProduct.getAuditStatus() != null){
			update.set("auditTime", skuProduct.getAuditStatus());
		}
		if(skuProduct.getSkus() != null){
			Map<String, SkuItemAttributeVO> skus = skuProduct.getSkus();
			update.set("skus", skus);
		}
		update.set("gmtModified", new Date());
		mongoTemplate.updateMulti(new Query(Criteria.where("productId").is(skuProduct.getProductId())), update, SKU_PRODUCT_COLLECTION);

		return new Result<String>(SkuResultCode.SUCCESS);
	}
	
	/**
	 * 根据skuBrandId查询
	 * shenpingfeng
	 * 2017年2月23日
	 * @param skuBrandId
	 * @return
	 */
	@Override
	public Result<List<SkuProductVO>> getProductBySkuBrandId(Integer skuBrandId) {
		if(skuBrandId == null){
			return new Result<List<SkuProductVO>>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		List<SkuProduct> skuProducts = skuProductMapper.selectProductBySkuBrandId(skuBrandId);
		if(skuProducts == null || skuProducts.size() == 0){
			return new Result<List<SkuProductVO>>(SkuResultCode.DATA_NOT_EXIST);
		}
		List<SkuProductVO> skuProductVOs = SkuProductConverter.toSkuProductVOs(skuProducts);		
		return new Result<List<SkuProductVO>>(skuProductVOs);
	}
	
	/**
	 * 根据条件查询
	 * shenpingfeng
	 * 2017年2月27日
	 * @param skuProductQueryVO
	 * @return
	 */
	@Override
	public Result<List<SkuProductVO>> getProductByStatement(SkuProductQueryVO skuProductQueryVO) {
		if (skuProductQueryVO == null) {
			return new Result<List<SkuProductVO>>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		Map<String, Object> params = convertSkuProductQueryVOToMap(skuProductQueryVO);
		List<SkuProduct> products = skuProductMapper.queryProductList(params, null);
		List<Integer> strategicSkuItemIdList = new ArrayList<>();
		Set<Integer> skuCategoryIdSet = new HashSet<>();
		List<Integer> productIdList = new ArrayList<>();
		for (SkuProduct skuProduct : products) {
			skuCategoryIdSet.add(skuProduct.getSkuCategoryId());
			productIdList.add(skuProduct.getProductId());
		}
		for (Integer skuCategoryId : skuCategoryIdSet) {
			Result<Integer> strategicSkuItemIdRes = skuItemManager.getStrategicSkuItemId(skuCategoryId);
			Integer strategicSkuItemId = null;
			if (strategicSkuItemIdRes.isSuccess()) {
				strategicSkuItemId = strategicSkuItemIdRes.getDataModel();
			}
			strategicSkuItemIdList.add(strategicSkuItemId);
		}
		List<SkuProductVO> skuProductVOs = SkuProductConverter.toSkuProductVOs(products);
		List<RelProductSkuAttribute> relProductSkuAttributeList = relProductSkuAttributeMapper.selectByProductIdsAndSkuItemIds
				(productIdList, strategicSkuItemIdList);
		Map<Integer, String> strategicPriceMap = new HashMap<>();
		if (relProductSkuAttributeList != null && relProductSkuAttributeList.size() > 0) {
			for (RelProductSkuAttribute relProductSkuAttribute : relProductSkuAttributeList) {
				strategicPriceMap.put(relProductSkuAttribute.getProductId(), relProductSkuAttribute.getValue());
			}
		}
		for (SkuProductVO skuProductVO : skuProductVOs) {
			try {
				skuProductVO.setStrategicPrice(new BigDecimal(strategicPriceMap.get(skuProductVO.getProductId())));
			} catch (Exception e) {
				LOGGER.error("推荐列表获取战略报价出错,productId=" + skuProductVO.getProductId());
			}
		}
		return new Result<List<SkuProductVO>>(skuProductVOs);
	}

}
